﻿using Caliburn.Micro;
using Microsoft.Win32;
using SD.Common;
using SD.Infrastructure.DTOBase;
using SD.Infrastructure.WPF.Caliburn.Aspects;
using SD.Infrastructure.WPF.Caliburn.Base;
using SD.Infrastructure.WPF.Extensions;
using SD.Infrastructure.WPF.Interfaces;
using SD.Infrastructure.WPF.Models;
using SD.IOC.Core.Mediators;
using SD.Toolkits.Excel;
using SlamDunk.MES.Client.ViewModels.Facility;
using SlamDunk.MES.IAppService.DTOs.Outputs.PlanContext;
using SlamDunk.MES.IAppService.DTOs.Outputs.ResourceContext;
using SlamDunk.MES.IAppService.Interfaces;
using SlamDunk.MES.Presentation;
using SlamDunk.MES.Presentation.Maps;
using SlamDunk.MES.Presentation.Models.ExportModels;
using SlamDunk.ValueObjects.Enums;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.ServiceModel.Extensions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;

namespace SlamDunk.MES.Client.ViewModels.ExecutionPlan
{
    /// <summary>
    /// 作业计划首页视图模型
    /// </summary>
    public class IndexViewModel : ScreenBase, IPaginatable
    {
        #region # 字段及构造器

        /// <summary>
        /// 资源定义服务契约接口代理
        /// </summary>
        private readonly ServiceProxy<IResourceContract> _resourceContract;

        /// <summary>
        /// 计划管理服务契约接口代理
        /// </summary>
        private readonly ServiceProxy<IPlanContract> _planContract;

        /// <summary>
        /// 窗口管理器
        /// </summary>
        private readonly IWindowManager _windowManager;

        /// <summary>
        /// 依赖注入构造器
        /// </summary>
        public IndexViewModel(ServiceProxy<IResourceContract> resourceContract, ServiceProxy<IPlanContract> planContract, IWindowManager windowManager)
        {
            this._resourceContract = resourceContract;
            this._planContract = planContract;
            this._windowManager = windowManager;

            //默认值
            this.PageIndex = 1;
            this.PageSize = 20;
        }

        #endregion

        #region # 属性

        #region 关键字 —— string Keywords
        /// <summary>
        /// 关键字
        /// </summary>
        [DependencyProperty]
        public string Keywords { get; set; }
        #endregion

        #region 开始时间 —— DateTime? StartTime
        /// <summary>
        /// 开始时间
        /// </summary>
        [DependencyProperty]
        public DateTime? StartTime { get; set; }
        #endregion

        #region 结束时间 —— DateTime? EndTime
        /// <summary>
        /// 结束时间
        /// </summary>
        [DependencyProperty]
        public DateTime? EndTime { get; set; }
        #endregion

        #region 页码 —— int PageIndex
        /// <summary>
        /// 页码
        /// </summary>
        [DependencyProperty]
        public int PageIndex { get; set; }
        #endregion

        #region 页容量 —— int PageSize
        /// <summary>
        /// 页容量
        /// </summary>
        [DependencyProperty]
        public int PageSize { get; set; }
        #endregion

        #region 总记录数 —— int RowCount
        /// <summary>
        /// 总记录数
        /// </summary>
        [DependencyProperty]
        public int RowCount { get; set; }
        #endregion

        #region 总页数 —— int PageCount
        /// <summary>
        /// 总页数
        /// </summary>
        [DependencyProperty]
        public int PageCount { get; set; }
        #endregion

        #region 已选产品 —— MaterialInfo SelectedProduct
        /// <summary>
        /// 已选产品
        /// </summary>
        [DependencyProperty]
        public MaterialInfo SelectedProduct { get; set; }
        #endregion

        #region 已选计划状态 —— ExecutionPlanStatus? SelectedPlanStatus
        /// <summary>
        /// 已选计划状态
        /// </summary>
        [DependencyProperty]
        public ExecutionPlanStatus? SelectedPlanStatus { get; set; }
        #endregion

        #region 已选审核状态 —— CheckStatus? SelectedCheckStatus
        /// <summary>
        /// 已选审核状态
        /// </summary>
        [DependencyProperty]
        public CheckStatus? SelectedCheckStatus { get; set; }
        #endregion

        #region 已选工厂模型 —— Node SelectedFacility
        /// <summary>
        /// 已选工厂模型
        /// </summary>
        [DependencyProperty]
        public Node SelectedFacility { get; set; }
        #endregion

        #region 作业计划列表 —— ObservableCollection<Wrap<ExecutionPlanInfo>> ExecutionPlans
        /// <summary>
        /// 作业计划列表
        /// </summary>
        [DependencyProperty]
        public ObservableCollection<Wrap<ExecutionPlanInfo>> ExecutionPlans { get; set; }
        #endregion

        #region 产品列表 —— ObservableCollection<MaterialInfo> Products
        /// <summary>
        /// 产品列表
        /// </summary>
        [DependencyProperty]
        public ObservableCollection<MaterialInfo> Products { get; set; }
        #endregion

        #region 计划状态字典 —— IDictionary<string, string> PlanStatuses
        /// <summary>
        /// 计划状态字典
        /// </summary>
        [DependencyProperty]
        public IDictionary<string, string> PlanStatuses { get; set; }
        #endregion

        #region 审核状态字典 —— IDictionary<string, string> CheckStatuses
        /// <summary>
        /// 审核状态字典
        /// </summary>
        [DependencyProperty]
        public IDictionary<string, string> CheckStatuses { get; set; }
        #endregion

        #endregion

        #region # 方法

        //Initializations

        #region 初始化 —— override async Task OnInitializeAsync(CancellationToken cancellationToken)
        /// <summary>
        /// 初始化
        /// </summary>
        protected override async Task OnInitializeAsync(CancellationToken cancellationToken)
        {
            IEnumerable<MaterialInfo> products = await Task.Run(() => this._resourceContract.Channel.GetMaterialsByPage(null, null, null, null, null, null, 1, int.MaxValue).Datas, cancellationToken);
            this.Products = new ObservableCollection<MaterialInfo>(products);

            this.PlanStatuses = typeof(ExecutionPlanStatus).GetEnumMembers();
            this.CheckStatuses = typeof(CheckStatus).GetEnumMembers();

            await this.ReloadExecutionPlans();
        }
        #endregion


        //Actions

        #region 选择工厂模型 —— async void SelectFacility()
        /// <summary>
        /// 选择工厂模型
        /// </summary>
        public async void SelectFacility()
        {
            this.Busy();

            SelectFacilityViewModel viewModel = ResolveMediator.Resolve<SelectFacilityViewModel>();
            bool? result = await this._windowManager.ShowDialogAsync(viewModel);
            if (result == true)
            {
                this.SelectedFacility = viewModel.SelectedFacility;
            }

            this.Idle();
        }
        #endregion

        #region 清空工厂模型 —— void ClearFacility()
        /// <summary>
        /// 清空工厂模型
        /// </summary>
        public void ClearFacility()
        {
            this.SelectedFacility = null;
        }
        #endregion

        #region 加载作业计划列表 —— async void LoadExecutionPlans()
        /// <summary>
        /// 加载作业计划列表
        /// </summary>
        public async void LoadExecutionPlans()
        {
            await this.ReloadExecutionPlans();
        }
        #endregion

        #region 创建作业计划 —— async void CreateExecutionPlan()
        /// <summary>
        /// 创建作业计划
        /// </summary>
        public async void CreateExecutionPlan()
        {
            AddViewModel viewModel = ResolveMediator.Resolve<AddViewModel>();
            await viewModel.Load(this.Products);
            bool? result = await this._windowManager.ShowDialogAsync(viewModel);
            if (result == true)
            {
                await this.ReloadExecutionPlans();
            }
        }
        #endregion

        #region 修改作业计划 —— async void UpdateExecutionPlan()
        /// <summary>
        /// 修改作业计划
        /// </summary>
        public async void UpdateExecutionPlan()
        {
            #region # 验证

            if (this.ExecutionPlans.Count(x => x.IsChecked == true) != 1)
            {
                MessageBox.Show("请勾选一条要修改的作业计划！", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            #endregion

            Wrap<ExecutionPlanInfo> executionPlan = this.ExecutionPlans.Single(x => x.IsChecked == true);

            #region # 验证

            if (executionPlan.Model.CheckStatus == CheckStatus.Checking)
            {
                MessageBox.Show("审核中的作业计划不可修改！", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }
            if (executionPlan.Model.CheckStatus == CheckStatus.Passed)
            {
                MessageBox.Show("审核通过的作业计划不可修改！", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            #endregion

            this.Busy();

            UpdateViewModel viewModel = ResolveMediator.Resolve<UpdateViewModel>();
            viewModel.Load(executionPlan.Model, this.Products);
            bool? result = await this._windowManager.ShowDialogAsync(viewModel);

            this.Idle();

            if (result == true)
            {
                await this.ReloadExecutionPlans();
            }
        }
        #endregion

        #region 设置生产物料需求 —— async void SetProductionMaterialAsks()
        /// <summary>
        /// 设置生产物料需求
        /// </summary>
        public async void SetProductionMaterialAsks()
        {
            #region # 验证

            if (this.ExecutionPlans.Count(x => x.IsChecked == true) != 1)
            {
                MessageBox.Show("请勾选一条要设置生产物料需求的作业计划！", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            #endregion

            Wrap<ExecutionPlanInfo> executionPlan = this.ExecutionPlans.Single(x => x.IsChecked == true);

            this.Busy();

            MaterialAskViewModel viewModel = ResolveMediator.Resolve<MaterialAskViewModel>();
            await viewModel.Load(executionPlan.Model);
            await this._windowManager.ShowDialogAsync(viewModel);

            this.Idle();
        }
        #endregion

        #region 删除作业计划 —— async void RemoveExecutionPlans()
        /// <summary>
        /// 删除作业计划
        /// </summary>
        public async void RemoveExecutionPlans()
        {
            #region # 加载勾选

            ExecutionPlanInfo[] checkedExecutionPlans = this.ExecutionPlans.Where(x => x.IsChecked == true).Select(x => x.Model).ToArray();
            if (!checkedExecutionPlans.Any())
            {
                MessageBox.Show("请勾选要删除的作业计划！", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            #endregion

            MessageBoxResult result = MessageBox.Show("确定要删除吗？", "警告", MessageBoxButton.YesNo, MessageBoxImage.Warning);
            if (result == MessageBoxResult.Yes)
            {
                this.Busy();

                IPlanContract planContract = this._planContract.Channel;
                await Task.Run(() => checkedExecutionPlans.ForEach(authority => planContract.RemoveExecutionPlan(authority.Id)));
                await this.ReloadExecutionPlans();

                this.Idle();
            }
        }
        #endregion

        #region 查看作业计划 —— async void LookExecutionPlan()
        /// <summary>
        /// 查看作业计划
        /// </summary>
        public async void LookExecutionPlan()
        {
            #region # 验证

            if (this.ExecutionPlans.Count(x => x.IsChecked == true) != 1)
            {
                MessageBox.Show("请勾选一条要查看的作业计划！", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            #endregion

            Wrap<ExecutionPlanInfo> executionPlan = this.ExecutionPlans.Single(x => x.IsChecked == true);

            this.Busy();

            LookViewModel viewModel = ResolveMediator.Resolve<LookViewModel>();
            await viewModel.Load(executionPlan.Model);
            await this._windowManager.ShowDialogAsync(viewModel);

            this.Idle();
        }
        #endregion

        #region 提交审核作业计划 —— async void SubmitExecutionPlans()
        /// <summary>
        /// 提交审核作业计划
        /// </summary>
        public async void SubmitExecutionPlans()
        {
            #region # 加载勾选

            ExecutionPlanInfo[] checkedExecutionPlans = this.ExecutionPlans.Where(x => x.IsChecked == true).Select(x => x.Model).ToArray();
            if (!checkedExecutionPlans.Any())
            {
                MessageBox.Show("请勾选要提交审核的作业计划！", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            #endregion

            MessageBoxResult result = MessageBox.Show("确定要提交审核吗？", "警告", MessageBoxButton.YesNo, MessageBoxImage.Warning);
            if (result == MessageBoxResult.Yes)
            {
                this.Busy();

                IPlanContract planContract = this._planContract.Channel;
                await Task.Run(() => planContract.SubmitExecutionPlans(checkedExecutionPlans.Select(x => x.Id)));
                await this.ReloadExecutionPlans();

                this.Idle();
            }
        }
        #endregion

        #region 审核作业计划 —— async void CheckExecutionPlan()
        /// <summary>
        /// 审核作业计划
        /// </summary>
        public async void CheckExecutionPlan()
        {
            #region # 验证

            if (this.ExecutionPlans.Count(x => x.IsChecked == true) != 1)
            {
                MessageBox.Show("请勾选一条要审核的作业计划！", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            #endregion

            Wrap<ExecutionPlanInfo> executionPlan = this.ExecutionPlans.Single(x => x.IsChecked == true);

            #region # 验证

            if (executionPlan.Model.CheckStatus != CheckStatus.Checking)
            {
                MessageBox.Show("只有审核中的作业计划可以审核！", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            #endregion

            this.Busy();

            CheckViewModel viewModel = ResolveMediator.Resolve<CheckViewModel>();
            await viewModel.Load(executionPlan.Model);
            bool? result = await this._windowManager.ShowDialogAsync(viewModel);

            this.Idle();

            if (result == true)
            {
                await this.ReloadExecutionPlans();
            }
        }
        #endregion

        #region 发布作业计划 —— async void ReleaseExecutionPlan()
        /// <summary>
        /// 发布作业计划
        /// </summary>
        public async void ReleaseExecutionPlan()
        {
            #region # 验证

            if (this.ExecutionPlans.Count(x => x.IsChecked == true) != 1)
            {
                MessageBox.Show("请勾选一条要发布的作业计划！", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            #endregion

            Wrap<ExecutionPlanInfo> executionPlan = this.ExecutionPlans.Single(x => x.IsChecked == true);

            #region # 验证

            if (executionPlan.Model.CheckStatus != CheckStatus.Passed)
            {
                MessageBox.Show("审核未通过的作业计划不可发布！", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }
            if (executionPlan.Model.Status != ExecutionPlanStatus.Waiting)
            {
                MessageBox.Show("只有等待状态的作业计划可以发布！", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            #endregion

            MessageBoxResult result = MessageBox.Show("确定要发布吗？", "警告", MessageBoxButton.YesNo, MessageBoxImage.Warning);
            if (result == MessageBoxResult.Yes)
            {
                this.Busy();

                await Task.Run(() => this._planContract.Channel.ReleaseExecutionPlan(executionPlan.Model.Id));
                await this.ReloadExecutionPlans();

                this.Idle();
            }
        }
        #endregion

        #region 取消作业计划 —— async void CancelExecutionPlan()
        /// <summary>
        /// 取消作业计划
        /// </summary>
        public async void CancelExecutionPlan()
        {
            #region # 验证

            if (this.ExecutionPlans.Count(x => x.IsChecked == true) != 1)
            {
                MessageBox.Show("请勾选一条要取消的作业计划！", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            #endregion

            Wrap<ExecutionPlanInfo> executionPlan = this.ExecutionPlans.Single(x => x.IsChecked == true);

            #region # 验证

            if (executionPlan.Model.Status != ExecutionPlanStatus.Waiting)
            {
                MessageBox.Show("只有等待状态的作业计划可以取消！", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            #endregion

            MessageBoxResult result = MessageBox.Show("确定要取消吗？", "警告", MessageBoxButton.YesNo, MessageBoxImage.Warning);
            if (result == MessageBoxResult.Yes)
            {
                this.Busy();

                await Task.Run(() => this._planContract.Channel.CancelExecutionPlan(executionPlan.Model.Id, null));
                await this.ReloadExecutionPlans();

                this.Idle();
            }
        }
        #endregion

        #region 中止作业计划 —— async void AbortExecutionPlan()
        /// <summary>
        /// 中止作业计划
        /// </summary>
        public async void AbortExecutionPlan()
        {
            #region # 验证

            if (this.ExecutionPlans.Count(x => x.IsChecked == true) != 1)
            {
                MessageBox.Show("请勾选一条要中止的作业计划！", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            #endregion

            Wrap<ExecutionPlanInfo> executionPlan = this.ExecutionPlans.Single(x => x.IsChecked == true);

            #region # 验证

            if (executionPlan.Model.Status != ExecutionPlanStatus.Released &&
                executionPlan.Model.Status != ExecutionPlanStatus.Executing)
            {
                MessageBox.Show("只有已发布和执行中的作业计划可以中止！", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            #endregion

            MessageBoxResult result = MessageBox.Show("确定要中止吗？", "警告", MessageBoxButton.YesNo, MessageBoxImage.Warning);
            if (result == MessageBoxResult.Yes)
            {
                this.Busy();

                await Task.Run(() => this._planContract.Channel.AbortExecutionPlan(executionPlan.Model.Id, null));
                await this.ReloadExecutionPlans();

                this.Idle();
            }
        }
        #endregion

        #region 完成作业计划 —— async void CompleteExecutionPlan()
        /// <summary>
        /// 完成作业计划
        /// </summary>
        public async void CompleteExecutionPlan()
        {
            #region # 验证

            if (this.ExecutionPlans.Count(x => x.IsChecked == true) != 1)
            {
                MessageBox.Show("请勾选一条要完成的作业计划！", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            #endregion

            Wrap<ExecutionPlanInfo> executionPlan = this.ExecutionPlans.Single(x => x.IsChecked == true);

            #region # 验证

            if (executionPlan.Model.Status != ExecutionPlanStatus.Executing)
            {
                MessageBox.Show("只有执行中的作业计划可以完成！", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            #endregion

            MessageBoxResult result = MessageBox.Show("确定要完成吗？", "警告", MessageBoxButton.YesNo, MessageBoxImage.Warning);
            if (result == MessageBoxResult.Yes)
            {
                this.Busy();

                await Task.Run(() => this._planContract.Channel.CompleteExecutionPlan(executionPlan.Model.Id));
                await this.ReloadExecutionPlans();

                this.Idle();
            }
        }
        #endregion

        #region 打印作业计划 —— async void PrintExecutionPlans()
        /// <summary>
        /// 打印作业计划
        /// </summary>
        public async void PrintExecutionPlans()
        {
            #region # 验证

            if (this.ExecutionPlans.All(x => x.IsChecked != true))
            {
                MessageBox.Show("请勾选至少一条要打印的作业计划！", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            #endregion

            IEnumerable<Wrap<ExecutionPlanInfo>> checkedWraps = this.ExecutionPlans.Where(x => x.IsChecked == true);

            this.Busy();

            PrintViewModel viewModel = ResolveMediator.Resolve<PrintViewModel>();
            viewModel.Load(checkedWraps.Select(x => x.Model));
            await this._windowManager.ShowDialogAsync(viewModel);

            this.Idle();
        }
        #endregion

        #region 导出作业计划 —— async void ExportExecutionPlans()
        /// <summary>
        /// 导出作业计划
        /// </summary>
        public async void ExportExecutionPlans()
        {
            string keywords = this.Keywords;
            Guid? productId = this.SelectedProduct?.Id;
            ExecutionPlanStatus? planStatus = this.SelectedPlanStatus;
            CheckStatus? checkStatus = this.SelectedCheckStatus;
            DateTime? startTime = this.StartTime;
            DateTime? endTime = this.EndTime;
            Guid? facilityId = this.SelectedFacility?.Id;
            PageModel<ExecutionPlanInfo> pageModel = await Task.Run(() => this._planContract.Channel.GetExecutionPlansByPage(keywords, productId, null, null, null, planStatus, checkStatus, null, null, startTime, endTime, facilityId, 1, int.MaxValue));

            ExecutionPlanEm[] executionPlanEms = pageModel.Datas.Select(x => x.ToExportView()).ToArray();
            if (!executionPlanEms.Any())
            {
                MessageBox.Show("导出数据为空，不能进行导出！", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            SaveFileDialog saveFileDialog = new SaveFileDialog
            {
                Filter = Constants.ExeclFileExtensionsFilter,
                FileName = $"作业计划_{DateTime.Now.ToString(Constants.ExportFileTimeFormat)}",
                AddExtension = true,
                RestoreDirectory = true
            };
            if (saveFileDialog.ShowDialog() == true)
            {
                string filePath = saveFileDialog.FileName;
                ExcelWriter.WriteFile(executionPlanEms, filePath);
            }
        }
        #endregion

        #region 全选 —— void CheckAll()
        /// <summary>
        /// 全选
        /// </summary>
        public void CheckAll()
        {
            this.ExecutionPlans.ForEach(x => x.IsChecked = true);
        }
        #endregion

        #region 取消全选 —— void UncheckAll()
        /// <summary>
        /// 取消全选
        /// </summary>
        public void UncheckAll()
        {
            this.ExecutionPlans.ForEach(x => x.IsChecked = false);
        }
        #endregion


        //Private

        #region 加载作业计划列表 —— async Task ReloadExecutionPlans()
        /// <summary>
        /// 加载作业计划列表
        /// </summary>
        private async Task ReloadExecutionPlans()
        {
            this.Busy();

            string keywords = this.Keywords;
            Guid? productId = this.SelectedProduct?.Id;
            ExecutionPlanStatus? planStatus = this.SelectedPlanStatus;
            CheckStatus? checkStatus = this.SelectedCheckStatus;
            DateTime? startTime = this.StartTime;
            DateTime? endTime = this.EndTime;
            Guid? facilityId = this.SelectedFacility?.Id;

            PageModel<ExecutionPlanInfo> pageModel = await Task.Run(() => this._planContract.Channel.GetExecutionPlansByPage(keywords, productId, null, null, null, planStatus, checkStatus, null, null, startTime, endTime, facilityId, this.PageIndex, this.PageSize));
            this.RowCount = pageModel.RowCount;
            this.PageCount = pageModel.PageCount;

            IEnumerable<Wrap<ExecutionPlanInfo>> wrapModels = pageModel.Datas.Select(x => x.Wrap());
            this.ExecutionPlans = new ObservableCollection<Wrap<ExecutionPlanInfo>>(wrapModels);

            this.Idle();
        }
        #endregion

        #endregion
    }
}
